<template>
    <div class="app-container">
      <h2>《{{this.$route.query.courseName}}》课程宣传资料</h2>
      <el-tag>课程封面</el-tag>
      <el-upload
        class="avatar-uploader"
        :action="uploads.url"
        :headers="uploads.headers"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
</template>


<script>
import { getToken } from "@/utils/auth";
import {  getCourse, updateCourse } from "@/api/teach/course";
    export default {
      data() {
        return {
          uploads: {
            // 是否禁用上传
            isUploading: false,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/common/upload",
            // 上传的文件列表
            fileList: [],
          },
          imageUrl: ''
        };
      },
      created(){
        getCourse(this.$route.query.courseId).then(response=>{
          this.imageUrl = process.env.VUE_APP_BASE_API+response.data.icon
        })
      },
      methods: {
        handleAvatarSuccess(res, file) {
          console.log(res)
          this.imageUrl = URL.createObjectURL(file.raw);
          updateCourse({id:this.$route.query.courseId,icon:res.fileName}).then(res=>{
            console.log(res)
          })
        },
        beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024 / 1024 < 2;

          if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
          }
          if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isJPG && isLt2M;
        }
      }
    }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #CCCCCC;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width:200px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #CCCCCC;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
